package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

/**
 * 吐槽 Service.
 *
 * @author 宫新程
 * @since 2019/3/3 23:58
 */
@Service
@Transactional
public class SpitService {

  @Resource private SpitDao spitDao;
  @Resource private IdWorker idWorker;
  @Resource private MongoTemplate mongoTemplate;

  /** 查询全部. */
  public List<Spit> findAll() {
    return spitDao.findAll();
  }

  /** 根据id查询. */
  public Spit findById(String spitId) {
    return spitDao.findById(spitId).get();
  }

  /** 保存. */
  public void save(Spit spit) {
    spit.set_id(idWorker.nextId() + "");
    spit.setPublishtime(new Date()); // 发布日期
    spit.setVisits(0); // 浏览量
    spit.setShare(0); // 分享数
    spit.setThumbup(0); // 点赞数
    spit.setComment(0); // 回复数
    spit.setState("1"); // 状态

    // 如果存在上级ID,评论，父吐槽的评论数 + 1
    if (spit.getParentid() != null && !"".equals(spit.getParentid())) {
      Query query = new Query();
      query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
      Update update = new Update();
      update.inc("comment", 1);
      mongoTemplate.updateFirst(query, update, "spit");
    }

    spitDao.save(spit);
  }

  /** 更新. */
  public void update(Spit spit) {
    spitDao.save(spit);
  }

  /** 删除. */
  public void delete(String spitId) {
    spitDao.deleteById(spitId);
  }

  /** 根据上级ID查询吐槽数据（分页）. */
  public Page<Spit> findByParentId(String parentid, int page, int size) {
    Pageable pageable = PageRequest.of(page - 1, size);
    return spitDao.findByParentid(parentid, pageable);
  }

  /** 点赞. */
  public void thumbup(String spitId) {
    // 方式一：
    //    Spit spit = spitDao.findById(spitId).get();
    //    spit.setThumbup((spit.getThumbup() == null ? 0 : spit.getThumbup()) + 1);
    //    spitDao.save(spit);

    // 方式二：使用mongo原生命令自增
    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(spitId));
    Update update = new Update();
    update.inc("thumbup", 1);
    mongoTemplate.updateFirst(query, update, "spit");
  }
}
